﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sisocana.Core.Models;
using Sisocana.Core.Interfaces;
using Sisocana.Core;
using SisocanaFronEnd.Models;
using System.IO;
using System.Text;
using System.Net;

namespace SisocanaFronEnd.Controllers
{
    public class DonationsController : SiteController
    {
        IONGDefinidaService _ongService;
        IDonacionService _donacionService;

        public DonationsController()
            : this(new ONGDefinidaService(),new DonacionService())
        {
        }

        public DonationsController(IONGDefinidaService ongService,IDonacionService donacionService)
        {
            _donacionService = donacionService;
            _ongService = ongService;
        }
      
        //
        // GET: /Donations/

        public ActionResult Index()
        {
            return View();
        }

        //[HttpPost]
        //public ActionResult Report(ReportMissingPersonViewModel model, string create)
        //{
        //    if (!ModelState.IsValid)
        //        return View();
        //    if (create != "Create a new record")
        //    {
        //        IList<PersonaDesaparecidaModel> personas = _personaProvider.GetSimilar(ViewBag.Site.id, model.nombre, model.apellido);
        //        if (personas.Count != 0)
        //        {
        //            model.personas = personas;
        //            return View(model);
        //        }
        //    }
        //    return View("MissingPerson", new MissingPersonViewModel(model.nombre, model.apellido));
        //}


        public ActionResult Donacion()
        {
            int idSitio = ViewBag.Site.id;

            //*********AGREGAR ACA EL CHECKEO DE ONG ACTIVA*********
            IList<ONGDefinidaModel> ongs = _ongService.GetAll(o => (o.sitioId == idSitio)&&(o.estadoDefinido=="A")&&(o.estadoONGGeneral=="A"));
            List<ONGDefinidaViewModel> lista = new List<ONGDefinidaViewModel>();
            foreach (ONGDefinidaModel ong in ongs)
            {
                lista.Add(new ONGDefinidaViewModel(ong.id.ToString(),ong.nombreONGDefinida + "-" + ong.ongName));
            }

            var list = new SelectList(new[]{
                                              new {ID="F",Name="Funds"},
                                              new{ID="G",Name="Goods"},
                                              new{ID="S",Name="Services"},
                                          },
                           "ID", "Name");
            ViewData["list"] = list;

            ViewData["ONGDefinidas"] = new SelectList(lista, "idONGDefinida", "desc");
            DonacionViewModel dvm = new DonacionViewModel();
            dvm.ongs = lista;

            if (lista.Count()==0)
                return View("SiteError", new MessageModel("Make a donation", "Error", "There is no ONG defined for this site."));
            return View(dvm);
        }

        [HttpPost]
        public ActionResult Donacion(DonacionViewModel dvm)
        {
            if (dvm.tipoDonacion == "F")
                return RedirectToAction("DonateFunds", "Donations", new { idONGDefinida = dvm.idSeleccionado });
            else if (dvm.tipoDonacion == "G")
                return RedirectToAction("DonateGoods", "Donations", new { idONGDefinida = dvm.idSeleccionado });
            else if (dvm.tipoDonacion == "S")
                return RedirectToAction("DonateServices", "Donations", new { idONGDefinida = dvm.idSeleccionado });


            int idSitio = ViewBag.Site.id;
            //*********AGREGAR ACA EL CHECKEO DE ONG ACTIVA*********
            IList<ONGDefinidaModel> ongs = _ongService.GetAll(o => o.sitioId == idSitio);
            List<ONGDefinidaViewModel> lista = new List<ONGDefinidaViewModel>();
            foreach (ONGDefinidaModel ong in ongs)
            {
                lista.Add(new ONGDefinidaViewModel(ong.id.ToString(), ong.nombreONGDefinida + "-" + ong.ongName));
            }

            var list = new SelectList(new[]{
                                              new {ID="F",Name="Funds"},
                                              new{ID="G",Name="Goods"},
                                              new{ID="S",Name="Services"},
                                          },
                           "ID", "Name");
            ViewData["list"] = list;

            ViewData["ONGDefinidas"] = new SelectList(lista, "idONGDefinida", "desc");
            dvm.ongs = lista;
            return View(dvm);
        }


            ////llenar el combo con todas las redes sociales disponibles.
            //IList<NoticiaModel> sources = _fService.GetAllNoticia();

            //IList<String> listac = new List<String>();

            //foreach (NoticiaModel source in sources)
            //{
            //    listac.Add(source.nombre);
            //}
            //SelectList lista = new SelectList(listac);
            //ViewData["NoticiaNombre"] = lista;
        public ActionResult DonateGoods(string idONGDefinida)
        {
            //cargo combo tipo de bien
            IList<String> listat = new List<String>();
            listat.Add("Perishable food");
            listat.Add("Dry food");
            listat.Add("Medicine");
            listat.Add("Furniture");
            listat.Add("Properties");
            listat.Add("Other");
            SelectList listaTipo = new SelectList(listat);
            ViewData["nombreDelBien"] = listaTipo;

            return View(new DonacionBienesModel() 
                                { fecha = DateTime.Now,
                                  idSitio = ViewBag.Site.id,
                                  idONGDefinida = Convert.ToInt32(idONGDefinida) });
        }
            


        [HttpPost]
        public ActionResult DonateGoods(DonacionBienesModel dbm)
        {
            try
            {
                int res = _donacionService.addDonacionBienes(dbm);
                if (res == 0)
                {
                    return View("Success", new MessageModel("Make a donation", "Thanks for your support!", "Your donation was successfully registered."));
                }
                else
                {
                    return View("SiteError", new MessageModel("Make a donation", "We're sorry...", "The donation could not be registered."));
                }
            }
            catch(Exception e)
            {
                return View("SiteError", new MessageModel("Make a donation", "An unexpected error has occured", e.Message));
            }
        }

        public ActionResult DonateServices(string idONGDefinida)
        {
            //cargo combo tipo de bien
            IList<String> listat = new List<String>();
            listat.Add("Guard");
            listat.Add("Doctor");
            listat.Add("Military");
            listat.Add("Nurse");
            listat.Add("Teacher");
            listat.Add("Other");
            SelectList listaTipo = new SelectList(listat);
            ViewData["nombreDelServicio"] = listaTipo;

            //cargo combo tipo de bien
            IList<String> listam = new List<String>();
            listam.Add("In the ONG");
            listam.Add("In the disasters location");
            listam.Add("Other");
            SelectList listaModo = new SelectList(listam);
            ViewData["formaDonacion"] = listaModo;

            DonacionServiciosModel dsm = new DonacionServiciosModel();
            dsm.idONGDefinida = Convert.ToInt32(idONGDefinida);
            dsm.idSitio = ViewBag.Site.id;
            return View("DonateServices",dsm);
        }



        [HttpPost]
        public ActionResult DonateServices(DonacionServiciosModel dsm)
        {
            if (dsm.idONGDefinida == 0)
                return RedirectToAction("Donacion");
            try
            {
                int res = _donacionService.addDonacionServicios(dsm);
                if (res == 0)
                {
                    return View("Success", new MessageModel("Make a donation", "Thanks for your support!", "Your donation was successfully registered."));
                }
                else
                {
                    return View("SiteError", new MessageModel("Make a donation", "We're sorry...", "The donation could not be registered."));
                }
            }
            catch(Exception e)
            {
                return View("SiteError", new MessageModel("Make a donation", "An unexpected error has occured", e.Message));
            }
        }

        public ActionResult DonateFunds(string idONGDefinida)
        {
            DonacionEconomicaModel dem = new DonacionEconomicaModel();
            dem.idONGDefinida = Convert.ToInt32(idONGDefinida);
            dem.idSitio = ViewBag.Site.id;
            ONGDefinidaService ongds = new ONGDefinidaService();
            ONGDefinidaModel ongdm = ongds.GetAll(o => (o.id == dem.idONGDefinida)).First();
            dem.nombreONGDefinida = ongdm.nombreONGDefinida.Trim();
            dem.paypalLogin = ongdm.paypalLogin.Trim();

            //Cargo la lista de tarjetas aceptadas
            IList<string> creditCards = new List<string>();
            creditCards.Add("Visa");
            creditCards.Add("MasterCard");
            creditCards.Add("Discover");
            creditCards.Add("American Express");
            SelectList lista = new SelectList(creditCards);
            ViewData["tipoTarjeta"] = lista;

            //Cargo las listas para la expiration date
            //Cargo lista de months
            List<KeyValuePair<string, string>> expirationDateMonths = new List<KeyValuePair<string, string>>();
            for (int i = 1; i <= 12; i++)
            {
                DateTime month = new DateTime(2000, i, 1);
                expirationDateMonths.Add(new KeyValuePair<string, string>(month.ToString("MM"), month.ToString("MMM")));
            }
            ViewData["ExpMonthSelectList"] = new SelectList(expirationDateMonths, "key", "value", DateTime.Today.ToString("MM"));

            //Cargo lista de years
            List<KeyValuePair<string, string>> expirationDateYears = new List<KeyValuePair<string, string>>();
            for (int i = 0; i <= 11; i++)
            {
                String year = (DateTime.Today.Year + i).ToString();
                expirationDateYears.Add(new KeyValuePair<string, string>(year, year));
            }
            ViewData["ExpYearSelectList"] = new SelectList(expirationDateYears, "key", "value", DateTime.Today.Year.ToString()); 

            
            return View("DonateFunds", dem);
        }


        [HttpPost]
        public ActionResult DonateFunds(DonacionEconomicaModel dem)
        {
            if (ModelState.IsValid)
            {
                dem.fechaVencimiento = new DateTime(Convert.ToInt32(dem.ExpYear), Convert.ToInt32(dem.ExpMonth), 1);
                if (dem.idONGDefinida == 0)
                    return RedirectToAction("Donacion");
                try
                {
                    if (dem.tipoTarjeta == "American Express")
                        dem.tipoTarjeta = "AE";
                    int res = _donacionService.addDonacionEconomica(dem);
                    if (res == 0)
                    {
                        return View("Success", new MessageModel("Make a donation", "Thanks for your support!", "Your donation was successfully registered."));
                    }
                    else
                    {
                        return View("SiteError", new MessageModel("Make a donation", "We're sorry...", "The donation could not be registered."));
                    }
                }
                catch(Exception e)
                {
                    return View("SiteError", new MessageModel("Make a donation", "An unexpected error has occured", e.Message));
                }
            }
            else
            {
                //Cargo la lista de tarjetas aceptadas
                IList<string> creditCards = new List<string>();
                creditCards.Add("Visa");
                creditCards.Add("MasterCard");
                creditCards.Add("Discover");
                creditCards.Add("American Express");
                SelectList lista = new SelectList(creditCards);
                ViewData["tipoTarjeta"] = lista;

                //Cargo las listas para la expiration date
                //Cargo lista de months
                List<KeyValuePair<string, string>> expirationDateMonths = new List<KeyValuePair<string, string>>();
                for (int i = 1; i <= 12; i++)
                {
                    DateTime month = new DateTime(2000, i, 1);
                    expirationDateMonths.Add(new KeyValuePair<string, string>(month.ToString("MM"), month.ToString("MMM")));
                }
                ViewData["ExpMonthSelectList"] = new SelectList(expirationDateMonths, "key", "value", DateTime.Today.ToString("MM"));

                //Cargo lista de years
                List<KeyValuePair<string, string>> expirationDateYears = new List<KeyValuePair<string, string>>();
                for (int i = 0; i <= 11; i++)
                {
                    String year = (DateTime.Today.Year + i).ToString();
                    expirationDateYears.Add(new KeyValuePair<string, string>(year, year));
                }
                ViewData["ExpYearSelectList"] = new SelectList(expirationDateYears, "key", "value", DateTime.Today.Year.ToString());


                return View("DonateFunds", dem);
            }
        }

        [HttpPost]
        public ActionResult PDT()
        {

            string transactionID = Request["txn_id"];
            string sAmountPaid = Request["payment_gross"];
            string payerId = Request["payer_id"];
            string idONGDefinida = Request["custom"];
            Decimal amountPaid = 0;
            Decimal.TryParse(sAmountPaid, out amountPaid);
            DonacionEconomicaModel dem = new DonacionEconomicaModel();
            dem.monto = (Convert.ToInt32(amountPaid)) / 100;
            dem.conPaypal = true;
            dem.transactionId = transactionID;
            dem.idONGDefinida = Convert.ToInt32(idONGDefinida);
            dem.paypalpayerID = payerId;
            _donacionService.addDonacionEconomica(dem);

            return View("Success", new MessageModel("Make a donation", "Thanks for your support!", "Your donation was successfully registered."));
        }

        //
        // GET: /Donations/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Donations/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Donations/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Donations/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        /// <summary>
        /// Handles the PDT Response from PayPal
        /// </summary>
        /// <returns></returns>
        /// 

    }
}
